//
//  NSString+Extension.m
//  聊天
//
//  Created by apple on 14-5-30.
//  Copyright (c) 2014年 ccc. All rights reserved.
//

#import "NSString+Extension.h"

@implementation NSString (Extension)

- (CGSize)sizeWithFont:(UIFont *)font maxSize:(CGSize)maxSize
{
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    dict[NSFontAttributeName] = font;
    CGSize textSize = [self boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:dict context:nil].size;
    return textSize;
}


//计算字符串的宽度
-(CGFloat)widthOfWithFont:(UIFont *)font andHeight:(CGFloat)height
{
    
    CGSize beforeSize = CGSizeMake(CGFLOAT_MAX, height);
    
    CGSize nowSize = [self sizeWithFont:font maxSize:beforeSize];
    
    return nowSize.width;
    
}

//计算文本的高度
- (CGFloat)heightWithFont:(UIFont*)font
            withLineWidth:(CGFloat)lineWidth{
    CGSize beforeSize = CGSizeMake(lineWidth, CGFLOAT_MAX);
    CGSize nowSize = [self sizeWithFont:font maxSize:beforeSize];
    return nowSize.height;
    
}

/*
 1.如果一条消息距离上一条消息的时间间隔超过5分钟，则在此消息上方显示时间
 2.如果是今天的消息，直接显示时间，如“18:45”
 3.如果是昨天的消息，显示昨天＋时间，如昨天 18:45
 4.如果是在往前的消息，显示日期＋时间，如12月7日 18:45
 5.如果是再往前的消息（非本年），显示年份日期+时间，如“2014年12月7日 18:45”
 */
+ (NSString *)stringWithPreviousTime:(NSString *)previousTime withLatterTime:(NSString *)latterTime
{
   
    NSString *showTimeStr = @"";
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    
    //NSDate *currentDate = [NSDate date];
    NSDate *previousDate = [NSString dateFromNSString:previousTime];
    NSDate *latterDate = [NSString dateFromNSString:latterTime];
    
    if (previousTime == nil) {
        [dateFormatter setDateFormat:@"HH:mm"];
        showTimeStr = [dateFormatter stringFromDate:latterDate];
        return showTimeStr;
    }
    
    NSTimeInterval previous = [previousDate timeIntervalSinceNow];
    //[currentDate timeIntervalSinceDate:previousDate];
    NSTimeInterval current = [latterDate timeIntervalSinceNow];
    //[currentDate timeIntervalSinceDate:latterDate];
    //判断间隔时间是否少于5分钟
    float intervalSecond = fabsf((float)current - (float)previous);
    
    if (intervalSecond > 5 * 60) {
        
        //判断时间是否是当天消息
        [dateFormatter setDateFormat:@"YYYYMMDD"];
        NSString *dayCurrentStr = [dateFormatter stringFromDate:[NSDate date]];
        NSString *dayLatterStr = [dateFormatter stringFromDate:latterDate];
        
        if ([dayCurrentStr isEqualToString:dayLatterStr]) {
            [dateFormatter setDateFormat:@"HH:mm"];
        }
        else
        {
            //判断时间是否是昨天
            NSString *previousZeroTimeStr = [NSString stringWithFormat:@"%@%@", [dateFormatter stringFromDate:previousDate], @"000000"];
            NSString *LatterZeroTimeStr = [NSString stringWithFormat:@"%@%@", [dateFormatter stringFromDate:latterDate], @"000000"];
            NSTimeInterval previousZeroTimeInterval = [[NSString dateFromNSString:previousZeroTimeStr] timeIntervalSinceNow];
            NSTimeInterval yesterdayPrevious = [previousDate timeIntervalSinceNow];
            NSTimeInterval zerotimeInterval = [[NSString dateFromNSString:LatterZeroTimeStr] timeIntervalSinceNow];
            if ((float)yesterdayPrevious > (float)zerotimeInterval && (float)yesterdayPrevious > (float)previousZeroTimeInterval)
            {
                [dateFormatter setDateFormat:@"昨天 HH:mm"];
            }
            else
            {
                //判断时间是否是当年
                [dateFormatter setDateFormat:@"YYYY"];
                NSString *yearCurrentStr = [dateFormatter stringFromDate:[NSDate date]];
                NSString *yearLatterStr = [dateFormatter stringFromDate:latterDate];
                if ([yearCurrentStr isEqualToString:yearLatterStr]) {
                    [dateFormatter setDateFormat:@"MM月dd日 HH:mm"];
                }
                else
                {
                    [dateFormatter setDateFormat:@"yyyy年MM月dd日 HH:mm"];
                }
            }
        }
        showTimeStr = [dateFormatter stringFromDate:latterDate];
        return showTimeStr;
    }
    else
    {
        //间隔时间少于5分钟
        return showTimeStr;
    }
}

+ (NSString *)stringFromNSDate:(NSDate *)aDate
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat : @"yyyyMMddHHmmSS"];
    return [formatter stringFromDate:aDate];
}
/*
 1.如果一条消息距离上一条消息的时间间隔超过0分钟，则在此消息上方显示时间
 2.如果是今天的消息，直接显示时间，如“18:45”
 3.如果是昨天的消息，显示昨天＋时间，如昨天 18:45
 4.如果是在往前的消息，显示日期＋时间，如12月7日 18:45
 5.如果是再往前的消息（非本年），显示年份日期+时间，如“2014年12月7日 18:45”
 */
+ (NSString *)stringPreviousTime:(NSString *)previousTime withLatterTime:(NSString *)latterTime
{
    
    NSString *showTimeStr = @"";
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    
    //NSDate *currentDate = [NSDate date];
    NSDate *previousDate = [NSString dateFromNSString:previousTime];
    NSDate *latterDate = [NSString dateFromNSString:latterTime];
    
    if (previousTime == nil) {
        [dateFormatter setDateFormat:@"HH:mm"];
        showTimeStr = [dateFormatter stringFromDate:latterDate];
        return showTimeStr;
    }
    
    NSTimeInterval previous = [previousDate timeIntervalSinceNow];
    //[currentDate timeIntervalSinceDate:previousDate];
    NSTimeInterval current = [latterDate timeIntervalSinceNow];
    //[currentDate timeIntervalSinceDate:latterDate];
    //判断间隔时间是否少于5分钟
    float intervalSecond = fabsf((float)current - (float)previous);
    
    if (intervalSecond > 0) {
        
        //判断时间是否是当天消息
        [dateFormatter setDateFormat:@"YYYYMMDD"];
        NSString *dayCurrentStr = [dateFormatter stringFromDate:[NSDate date]];
        NSString *dayLatterStr = [dateFormatter stringFromDate:latterDate];
        
        if ([dayCurrentStr isEqualToString:dayLatterStr]) {
            [dateFormatter setDateFormat:@"HH:mm"];
        }
        else
        {
            //判断时间是否是昨天
            NSString *previousZeroTimeStr = [NSString stringWithFormat:@"%@%@", [dateFormatter stringFromDate:previousDate], @"000000"];
            NSString *LatterZeroTimeStr = [NSString stringWithFormat:@"%@%@", [dateFormatter stringFromDate:latterDate], @"000000"];
            NSTimeInterval previousZeroTimeInterval = [[NSString dateFromNSString:previousZeroTimeStr] timeIntervalSinceNow];
            NSTimeInterval yesterdayPrevious = [previousDate timeIntervalSinceNow];
            NSTimeInterval zerotimeInterval = [[NSString dateFromNSString:LatterZeroTimeStr] timeIntervalSinceNow];
            if ((float)yesterdayPrevious > (float)zerotimeInterval && (float)yesterdayPrevious > (float)previousZeroTimeInterval)
            {
                [dateFormatter setDateFormat:@"昨天 HH:mm"];
            }
            else
            {
                //判断时间是否是当年
                [dateFormatter setDateFormat:@"YYYY"];
                NSString *yearCurrentStr = [dateFormatter stringFromDate:[NSDate date]];
                NSString *yearLatterStr = [dateFormatter stringFromDate:latterDate];
                if ([yearCurrentStr isEqualToString:yearLatterStr]) {
                    [dateFormatter setDateFormat:@"MM月dd日 HH:mm"];
                }
                else
                {
                    [dateFormatter setDateFormat:@"yyyy年MM月dd日 HH:mm"];
                }
            }
        }
        showTimeStr = [dateFormatter stringFromDate:latterDate];
        return showTimeStr;
    }
    else
    {
        //间隔时间少于5分钟
        return showTimeStr;
    }
}

+ (NSDate *)dateFromNSString:(NSString *)aString
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyyMMddHHmmSS"];
    NSDate *timeDate = [formatter dateFromString:aString];
    return timeDate;
}

//传入 秒  得到 xx:xx:xx
+ (NSString *)getMMSSFromSS:(NSInteger )totalseconds
{
    //format of hour
    NSString *str_hour = [NSString stringWithFormat:@"%02ld",totalseconds/3600];
    //format of minute
    NSString *str_minute = [NSString stringWithFormat:@"%02ld",(totalseconds%3600)/60];
    //format of second
    NSString *str_second = [NSString stringWithFormat:@"%02ld",totalseconds%60];
    //format of time
    NSString *format_time = [NSString stringWithFormat:@"%@:%@:%@",str_hour,str_minute,str_second];
    
    return format_time;
    
}

//时间转化为 时分秒
+ (NSString *)getFenMMSSFrom:(NSInteger)totalSeconds
{
    NSString *finalStr ;
    //format of hour
    NSString *str_hour = [NSString stringWithFormat:@"%02ld",totalSeconds/3600];
    //format of minute
    NSString *str_minute = [NSString stringWithFormat:@"%02ld",(totalSeconds%3600)/60];
    //format of second
    NSString *str_second = [NSString stringWithFormat:@"%02ld",totalSeconds%60];
    if ([str_hour integerValue] != 0) {
        if ([str_minute integerValue] != 0){
            finalStr = [NSString stringWithFormat:@"%ld时%ld分%ld秒",[str_hour integerValue],[str_minute integerValue],[str_second integerValue]];
        }else{
            finalStr = [NSString stringWithFormat:@"%ld时%ld秒",[str_hour integerValue],[str_second integerValue]];
        }
    }else if ([str_minute integerValue] != 0){
        finalStr = [NSString stringWithFormat:@"%ld分%ld秒",[str_minute integerValue],[str_second integerValue]];
    }else if ([str_second integerValue] != 0){
        finalStr = [NSString stringWithFormat:@"%ld秒",[str_second integerValue]];
    }else{
        finalStr = @"0秒";
    }
    
    return finalStr;
}


/**
 *  调整字符串  主要是针对字符串过长 and 包含空格等情况的处理
 *
 *  @return
 */
+ (NSString *)changeStrWithLengthAndHuanhagfuWithStr:(NSString*)origalStr
{
    if(origalStr.length > 2020){
        origalStr = [NSString stringWithFormat:@"%@...",[origalStr substringToIndex:2020]];
    }
    NSString *resultStr;
    
    NSArray *strArray = [origalStr componentsSeparatedByString:@"\n"];
    
    if (strArray.count > 0) {
        resultStr = strArray[0];
    }
    
    if(kScreenBoundWidth == 320 && resultStr.length > 50){
        resultStr = [NSString stringWithFormat:@"%@...",[resultStr substringToIndex:50]];
        
    }else if(resultStr.length > 70){
        resultStr = [NSString stringWithFormat:@"%@...",[resultStr substringToIndex:70]];
    }

    return resultStr;
    
    return nil;
    
}

@end
